<template>
  <div class="music-list mt-5">
    <div class="list">
      <div class="title justify-between" :class="titleStyle" v-if="listPlaylistDetails?.trackCount">
        <div class="left flex items-end mb-1">
          <h3 class="mt-2 mb-0">歌曲列表</h3>
          <span class="ml-2 text-sm text-gray yu-titleColor">{{ listPlaylistDetails?.trackCount }}首歌</span>
        </div>
        <span class="text-sm" v-if="listPlaylistDetails?.playCount">
          <span>播放：</span>
          <span class="text-red-500 yu-titleColor">{{ listPlaylistDetails?.playCount }}</span>
          <span>次</span>
        </span>
      </div>
      <div class="title justify-between" :class="titleStyle" v-if="listPlaylistDetails?.programCount">
        <div class="left flex items-end mb-1">
          <h3 class="mt-2 mb-0">节目列表</h3>
          <span class="ml-2 text-sm text-gray yu-titleColor">共{{ listPlaylistDetails?.programCount }}期</span>
        </div>
      </div>
      <div class="content w-full">
        <table class="table box-border">
          <thead v-if="store.isFlag">
          <tr v-show="isHeader">
            <th>下标</th>
            <th>歌曲标题</th>
            <th>时长</th>
            <th>歌手</th>
            <th v-if="store.currentInfo.type !== 2">专辑</th>
          </tr>
          </thead>
          <tbody>
          <tr
              v-for="(songUrl, index) in paginationPlaylist"
              :key="isRadio(songUrl, 'id')"
              :class="[store.playlistInfo[store.songUrlIndex]?.id === songUrl.id ? 'yu-bgColor-two-active-only' : ''] "
              class="text-sm h-12 yu-bgColor-hover-only"
              @mousemove="mousemove(index)"
              @mouseleave="mouseleave"
              @click="playMusic(isRadio(songUrl, 'id'))"
          >
            <td>
              <div :class="titleStyle" class="justify-around h-full" v-if="store.isFlag ? 'text-xl' : 'text-sm'">
                <span class=" text-center">{{ index + 1 }}</span>
                <span :class="cursorPointerText" class=" i-mdi-play-circle-outline"
                      @click="playMusic(isRadio(songUrl, 'id'))"/>
              </div>
            </td>
            <td class="pl-4 text-justify">
              <div :class="titleStyle" class="justify-between relative">
                <div class="truncate" :class="store.isFlag ? 'w-65' : 'w-55' ">
                  <span :class="[cursorPointerText, store.isFlag ? '' : 'pt-2 pb-2']"
                        @click.stop="jumpPcSongDetail(isRadio(songUrl, 'id'), songUrl)">{{ songUrl.name }}</span>
                  <span v-if="isOther" v-show="songUrl.alia.length > 0"
                        class=" ml-2 yu-titleColor yu-textColor-hover cursor-pointer"> - ({{ songUrl.alia[0] }})</span>
                  <div v-if="!store.isFlag" class="w-56 flex text-justify truncate text-xs yu-titleColor"
                       :class="cursorPointerText">
                    <span v-if="isMusic" :class="store.isFlag ? '' : 'pb-2'"
                          @click.stop="jumpArtistDetails(songUrl.ar[0].id)">{{ songUrl.ar[0].name }}</span>
                    <i v-if="isMusic" class="ml-2 mr-2">/</i>
                    <span v-if="isMobileSinger" class="flex-1" @click.stop="jumpAlbum(songUrl.al.id)"
                          :class="[cursorPointerText, store.isFlag ? '' : 'pb-2']">{{ songUrl.al.name }}</span>
                  </div>
                </div>
                <span :class="cursorPointerText" v-show="songUrl.mv"
                      class="i-mdi-television-play ml-2 yu-color-text absolute right-3" @click.stop="jumpMv(songUrl)"></span>
              </div>
            </td>
            <td class="pl-4" v-if="store.isFlag">
              <div class="flex w-25 yu-color-text">
                <div
                    v-if="isActions === index"
                    class="flex items-center text-xl"
                >
                  <van-icon
                      v-if="store.token && isAddPlayList"
                      class-prefix="i-mdi-pencil-plus"
                      :class="cursorPointerText"
                      @click.stop="addMyPlaylist(isRadio(songUrl, 'id'))"
                  />
                  <span
                      v-if="isDownload"
                      class=" i-mdi-download"
                      :class="cursorPointerText"
                      @click.stop="downloadUrl(songUrl)"
                  />
                  <span
                      class="i-mdi-shape-rectangle-plus"
                      :class="cursorPointerText"
                      @click.stop="additionalSongs(isRadio(songUrl, 'id'))"
                  />
                  <span
                      v-if="store.token"
                      :class="cursorPointerText"
                      class="inline-block i-mdi-share mr-2"
                      @click.stop="shareMusicPopup(songUrl)"
                  />
                  <span
                      v-if="listPlaylistDetails?.creator?.userId === store.userInfo.userId"
                      class="inline-block i-mdi-delete"
                      :class="cursorPointerText"
                      @click.stop="delMyPlaylistMusic(songUrl)"
                  />
                </div>
                <span v-else>{{ timestampToSecondsMinutes(currentPlayTime(songUrl)) }}</span>
              </div>
            </td>
            <td class="pl-4 w-40" v-if="store.isFlag && isSong">
              <div class="w-40 truncate">
                <span
                    :class="cursorPointerText"
                    v-for="(ar, arIndex) in artistsFn(songUrl)"
                    :key="ar.id"
                    @click.stop="jumpArtistDetails(ar.id)"
                >
                {{ ar.name }}
                  <span v-if="arIndex < (songUrl?.ar?.length - 1 || songUrl?.artists?.lang - 1)"
                        class="ml-1 mr-1">/</span>
              </span>
              </div>
            </td>

            <td class="pl-4" v-if="store.isFlag && (store.currentInfo.type !== 2 || store.currentInfo.type === 5 )">
              <span v-if="isOther" class="w-30 truncate" :class="cursorPointerText"
                    @click.stop="jumpAlbum(songUrl.al.id)">{{ songUrl.al.name }}</span>
              <span v-if="isMusicNum" class="w-30 truncate" :class="cursorPointerText">听歌{{
                  songUrl.playCount
                }}次</span>
              <span v-if="isRadioPlayNum" class="w-35 truncate">播放{{
                  transition(songUrl.listenerCount)
                }}次 - 赞{{ songUrl.likedCount }}</span>
            </td>
            <td v-if="store.currentInfo.type === 5 && store.isFlag">
              <span class="w-20">{{ timestampToYMD(songUrl.scheduledPublishTime) }}</span>
            </td>
            <td class="pl-4" v-if="store.isFlag && isProduction">
              <span class="w-35 truncate yu-textColor-hover"
                    @click.stop="jumpAlbum(songUrl?.album?.id)">{{ songUrl?.album?.name }}</span>
            </td>
            <td v-if="!store.isFlag">
              <span class="i-mdi-format-list-bulleted inline-block" @click.stop="actionsPopup(songUrl)"></span>
            </td>
          </tr>
          </tbody>
        </table>
      </div>
      <div class="pagination mt-2 mb-2" v-if="store.currentInfo.type !== 2">
        <div v-if="noShowPage">
          <van-pagination
              v-if="listPlaylistDetails?.trackCount > 20"
              class="van-pagination"
              v-model="currentPage"
              :total-items="listPlaylistDetails?.trackCount"
              :items-per-page="20"
              :show-page-size="6"
              force-ellipses
              @change="pageChange"
          >
            <template #prev-text>
              <van-icon name="arrow-left"/>
            </template>
            <template #next-text>
              <van-icon name="arrow"/>
            </template>
            <template #page="{ text }">{{ text }}</template>
          </van-pagination>
        </div>
      </div>
    </div>
    <!-- 添加音乐到我的歌单 -->
    <add-playlist/>
    <!-- 分享弹窗 -->
    <share-popup ref="sharepopupExamples" :sharePlayerInfo="shareMusicInfo"/>
    <!-- 移动端操作按钮弹窗 -->
    <mobile-popup-actions
        ref="mobile_Actions"
        :song-url-info="songUrlInfo"
        :isMobileSinger="isMobileSinger"
        :isDownload="isDownload"
        :isAddPlayList="isAddPlayList"
        @playerMusic="playMusic"
        @addMyPlaylist="addMyPlaylist"
        @downloadUrl="downloadUrl"
        @shareMusicPopup="shareMusicPopup"
        @additionalSongs="additionalSongs"
    />
  </div>
</template>

<script setup>
import {useStore} from "@/store/index"
import {reactive, ref, toRefs} from "vue";
import {timestampToSecondsMinutes} from "@/utils/index";
import {asString, timestampToYMD} from "@/utils/index";
import transition from '@/hooks/filter'
import MobilePopupActions from './components/MobilePopupActions/index.vue'
import {useRoute, useRouter} from "vue-router";
import {getPlaylistTracks} from "../../api/login/index.js";

const data = reactive({
  titleStyle: 'flex items-center',
  cursorPointerText: 'cursor-pointer yu-textColor-hover',
  cursorPointerBg: 'cursor-pointer hover:bg-red-600 hover:text-white',
  songUrlInfo: {} // 移动端传递操作弹窗的数据
})
const {titleStyle, cursorPointerText, songUrlInfo} = toRefs(data)
const router = useRouter()
const route = useRoute()
const store = useStore()
// 移动端操作按钮弹窗实例
const mobile_Actions = ref(null)

// 分页默认展示哪个数据
const currentPage = ref(1)

// 分享弹窗实例
const sharepopupExamples = ref(null)
// 分享弹窗传递数据
const shareMusicInfo = ref({})
// 显示隐藏操作按钮
const isActions = ref()

// 分页改变会触发
const pageChange = (value) => {
// 由于这个分页数据需要通过limit控制返回数量和offset偏移量，所以直接通过num控制返回多少
  store.getPlaylistTrackAll(value)
}

// 将歌曲添加到我的歌单
const addMyPlaylist = (id = '') => {
  store.addPlaylistPopup = true
  if (id) {
    // 存放添加歌曲的id
    store.musicId = id.toString()
  } else {
    store.musicId = asString(store.privilegesTracks)
  }
}
// 下载音乐
const downloadUrl = (songUrl) => {
  let params
  switch (store.currentInfo.type) {
      // 电台
    case 5:
      params = {id: songUrl.mainSong.id, musicName: songUrl.mainSong.name, singerName: songUrl.mainSong.artists[0].name}
      break;
      // 电台节目相似歌曲
    case 6:
      params = {id: songUrl.id, musicName: songUrl.name, singerName: songUrl.artists[0].name}
      break;
    default:
      params = {id: songUrl.id, musicName: songUrl.name, singerName: songUrl.ar[0].name}
      break;
  }
  // 电台下载和其他音乐下载不同

  store.getSongDownloadUrl(params)
}
// 追加歌曲到播放列表
const additionalSongs = (id) => {
  store.getSongDetail(id, true)
}

// 播放歌曲
const playMusic = (id) => {
  console.log(id)
  store.getSongDetail(id)
}

// 分享歌曲弹窗
const shareMusicPopup = (params) => {
// 分享电台节目
  if (store.currentInfo.type === 5) {
    shareMusicInfo.value = {
      type: '节目',
      name: params.mainSong.name,
      publicId: params.id,
      shareType: 'djprogram' // 是电台
    }
  } else {
    shareMusicInfo.value = {
      type: '歌曲',
      name: params.name,
      publicId: params.id,
      shareType: 'song' // 判断分享的是歌曲还是其他
    }
  }

  sharepopupExamples.value.yuPopupA()
}

// 判断是否是电台
const isRadio = (params, info) => {
  if (store.currentInfo.type === 5) {
    return params.mainSong[info]
  } else {
    return params[info]
  }
}

// 显示和隐藏操作按钮
const mousemove = (index) => {
  isActions.value = index
}
// pc鼠标离开不显示操作按钮
const mouseleave = () => {
  isActions.value = -1
}
// mobile点击展开操作框
const actionsPopup = (songUrl) => {
  // console.log(songUrl)
  data.songUrlInfo = songUrl
  // console.log(songUrl)
  mobile_Actions.value.actions = true
}

// 跳转到当前歌曲的详情
const jumpPcSongDetail = (id, songUrl) => {
  let path
  // 判断是否是电台从电台跳转到电台详情
  if (store.currentInfo.type === 5) {
    id = songUrl.id
    path = '/radio-program'
  } else {
    path = '/pc-song-detail'
  }
  router.push({
    path,
    query: {
      id
    }
  })
}

// 点击专辑跳转到专辑页面
const jumpAlbum = (id) => {
  router.push({
    path: '/collection-detail',
    query: {
      id
    }
  })
}

// 跳转到歌手详情
const jumpArtistDetails = (id) => {
  router.push({
    path: '/artist',
    query: {
      id
    }
  })
}


// 接受父组件传递的参数
const props = defineProps({
  listPlaylistDetails: Object, // 歌单信息
  paginationPlaylist: Array, // 歌曲列表
  isHeader: { // 是否显示表头
    type: Boolean,
    default: true
  },
  // 是否展示分页
  noShowPage: {
    type: Boolean,
    default: true
  },
  isOther: { // 是否展示其他信息
    type: Boolean,
    default: true
  },
  // 是否展示歌手
  isSong: {
    type: Boolean,
    default: true
  },
  // 是否显示歌手名称
  isMusic: {
    type: Boolean,
    default: true
  },
  // 是否显示听歌次数
  isMusicNum: {
    type: Boolean,
    default: false
  },
  // 移动端是否显示歌手
  isMobileSinger: {
    type: Boolean,
    default: true
  },
  // 是否显示下载按钮
  isDownload: {
    type: Boolean,
    default: true
  },
  // 是否显示添加到我的歌单
  isAddPlayList: {
    type: Boolean,
    default: true
  },
  // 电台节目播放次数
  isRadioPlayNum: {
    type: Boolean,
    default: false
  },
  // 是否展示作品 一般只有电台节目需要展示
  isProduction: {
    type: Boolean,
    default: false
  }
})

const currentPlayTime = (songUrl) => {
  switch (store.currentInfo.type) {
    case 5:
      return songUrl?.mainSong?.duration
    case 6:
      return songUrl?.duration
    default:
      return songUrl?.dt
  }
}

const artistsFn = (songUrl) => {
  switch (store.currentInfo.type) {
    case 6:
      return songUrl?.artists
    default:
      return songUrl?.ar
  }
}

const $emit = defineEmits(['delMyPlaylistMusicSuccess'])
// 从我的歌单中移除歌曲
const delMyPlaylistMusic = (song) => {

  getPlaylistTracks({
    op: 'del',
    pid: route.query.id,
    tracks: song.id
  }).then(res => {
    console.log(res)
  }).catch(e => {
    if (e.status === 200) $emit('delMyPlaylistMusicSuccess')
  })

}
// 跳转到mv
const jumpMv = (songUrl) => {
  router.push({
    path: '/mv',
    query: {
      id: songUrl.mv
    }
  })
  console.log(songUrl)
}
</script>

<style scoped lang="scss">
.content {
  .table {
    width: 100%;
    border-collapse: collapse;
    border-top: v-bind('store.theme.textColor') solid 2px;
    border-bottom: v-bind('store.theme.titleTextColor') solid 1px;
    border-left: v-bind('store.theme.titleTextColor') solid 1px;
    border-right: v-bind('store.theme.titleTextColor') solid 1px;

    span {
      display: inline-block;
    }

    th {
      height: 40px;
      border: 1px solid v-bind('store.theme.titleTextColor');
    }

    td {
      height: 30px;
    }
  }
}

:deep(.van-pagination) {

  .van-pagination__item--prev, .van-pagination__item--next {

  }

  .van-pagination__item--active {
    color: v-bind('store.theme.hoverTextColor') !important;
  }

  .van-pagination__item--page, .van-pagination__item--next, .van-pagination__item--prev {
    color: v-bind('store.theme.textColor');

    button {
      background-color: v-bind('store.theme.HoverBgColor');
    }
  }
}

</style>
